package com.xingkeduo.service.api.marketing.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.xingkeduo.dao.TActivityCodeMapper;
import com.xingkeduo.dao.TActivityDaysMapper;
import com.xingkeduo.dao.TMarketingCardMapper;
import com.xingkeduo.dao.TMarketingCouponBagMapper;
import com.xingkeduo.dao.TMarketingCouponMapper;
import com.xingkeduo.dao.TMarketingMapperSpec;
import com.xingkeduo.dao.TMarketingReceiveHistoryCardMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponBagMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponMapper;
import com.xingkeduo.dao.TMarketingRelevantMapper;
import com.xingkeduo.dao.TMarketingRelevantMapperSpec;
import com.xingkeduo.dao.TServiceMapper;
import com.xingkeduo.enums.DictMarketingEnum;
import com.xingkeduo.feign.OrderFeignService;
import com.xingkeduo.model.example.TActivityCodeExample;
import com.xingkeduo.model.example.TActivityDaysExample;
import com.xingkeduo.model.example.TMarketingCouponBagExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCardExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponBagExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponExample;
import com.xingkeduo.model.example.TMarketingRelevantExample;
import com.xingkeduo.model.example.TServiceExample;
import com.xingkeduo.model.param.ActivityCodeParam.ActivityCodeStatusEnum;
import com.xingkeduo.model.param.MarketingParam;
import com.xingkeduo.model.param.MarketingParam.MarketingCouponBagTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingReceiveTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingServiceTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingStatusEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.AuthStatusEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveSendTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveStatusEnum;
import com.xingkeduo.model.param.VerifyReedRedeemCodeParam;
import com.xingkeduo.model.po.TActivityCode;
import com.xingkeduo.model.po.TActivityDays;
import com.xingkeduo.model.po.TDictMarketing;
import com.xingkeduo.model.po.TMarketing;
import com.xingkeduo.model.po.TMarketingCouponBag;
import com.xingkeduo.model.po.TMarketingReceiveHistory;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCardWithBLOBs;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCoupon;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCouponBag;
import com.xingkeduo.model.po.TMarketingRelevant;
import com.xingkeduo.model.po.TService;
import com.xingkeduo.model.vo.ActivityDaysResponseVo;
import com.xingkeduo.model.vo.MarketingResponseVo;
import com.xingkeduo.model.vo.MarketingValuePackResponseVo;
import com.xingkeduo.service.api.common.CommonService;
import com.xingkeduo.service.api.marketing.ReceiveService;
import com.xingkeduo.service.base.MarketingService;
import com.xingkeduo.service.cms.marketing.InventoryService;
import com.xingkeduo.service.consume.UserService;
import com.xingkeduo.service.dict.DictMarketingService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.RedisKeyEnum;
import com.xingkeduo.util.WeekUtil;
import com.xingkeduo.util.tool.ResponseMessage;

@Service
public class ReceiveServiceImpl implements ReceiveService {
	Logger logger = LoggerFactory.getLogger(ReceiveServiceImpl.class);

	@Autowired
	TMarketingCouponMapper tMarketingCouponMapper;
	@Autowired
	TMarketingCardMapper tMarketingCardMapper;
	@Autowired
	TMarketingCouponBagMapper tMarketingCouponBagMapper;
	@Autowired
	TActivityDaysMapper tActivityDaysMapper;
	@Autowired
	TActivityCodeMapper tActivityCodeMapper;
	@Autowired
	TMarketingRelevantMapper tMarketingRelevantMapper;
	@Autowired
	InventoryService inventoryService;
	@Autowired
	TMarketingMapperSpec tMarketingMapperSpec;
	@Autowired
	TServiceMapper tServiceMapper;
	@Autowired
	CommonService commonService;
	@Autowired
	TMarketingRelevantMapperSpec tMarketingRelevantMapperSpec1;
	@Autowired
	TMarketingReceiveHistoryCardMapper tMarketingReceiveHistoryCardMapper;
	@Autowired
	TMarketingReceiveHistoryCouponMapper tMarketingReceiveHistoryCouponMapper;
	@Autowired
	TMarketingReceiveHistoryCouponBagMapper tMarketingReceiveHistoryCouponBagMapper;
	@Autowired
	OrderFeignService orderFeignService;
	@Autowired
	DictMarketingService dictMarketingService;
	@Autowired
	ReceiveService receiveService;
	@Autowired
	UserService userService;
	@Autowired
	MarketingService marketingService;

	@Override
	public ResponseMessage queryMarketingDetailById(MarketingParam marketingParam) {
		// 卡，券信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingParam.getId(), marketingParam.getMarketingType());
		if (marketing == null) {
			return ResponseMessage.error("该卡券无效", 500);
		}
		MarketingResponseVo marketingResponseVO = new MarketingResponseVo();
		BeanUtils.copyProperties(marketing, marketingResponseVO);
		if(StringUtils.isNotBlank(marketingResponseVO.getStoreIds())) {
			String storeIds = marketingResponseVO.getStoreIds();
			if(storeIds.startsWith("0,")) {
				storeIds = storeIds.substring(2, storeIds.length());
			}
			if(storeIds.endsWith(",0")) {
				storeIds = storeIds.substring(0, storeIds.length()-2);
			}
			marketingResponseVO.setStoreIds(storeIds);
		}
		StringBuffer daysInfo = new StringBuffer();
		if(StringUtils.isNotBlank(marketing.getWeekHourIds()) 
				&& (!marketing.getWeekHourIds().equals("0"))) {
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(marketing.getId()).andStatusEqualTo(Constant.STATUS_YES)
					.andActivityTypeEqualTo(marketing.getMarketingType());
			example.setOrderByClause(" dayids desc");
			// 卡券活动时间
			List<TActivityDays> days = tActivityDaysMapper.selectByExample(example);
			List<ActivityDaysResponseVo> daysVo = new ArrayList<ActivityDaysResponseVo>();
			for (TActivityDays day : days) {
				ActivityDaysResponseVo activityDaysResponseVo = new ActivityDaysResponseVo();
				BeanUtils.copyProperties(day, activityDaysResponseVo);
				daysVo.add(activityDaysResponseVo);
				String daysIds = day.getDayids();
				if (daysIds.startsWith(",")) {
					daysIds = daysIds.substring(1, daysIds.length());
				}
				if (daysIds.endsWith(",")) {
					daysIds = daysIds.substring(0, daysIds.length() - 1);
				}
				daysInfo.append(WeekUtil.convertWeek(daysIds)).append(", ")
						.append(DateUtils.formatDate(day.getStartTime(), DateUtils.TIME_FORMAT)).append("-")
						.append(DateUtils.formatDate(day.getEndTime(), DateUtils.TIME_FORMAT)).append("; ");
			}
			// 卡券添加活动时间
			marketingResponseVO.setActivityDays(daysVo);
		}
		if(StringUtils.isBlank(daysInfo.toString())){
			daysInfo.append("0:00-24:00");
		}
		marketingResponseVO.setDayMemo(daysInfo.toString());
		// 领取规则验证
		ResponseMessage message = marketingRuleReceiveValidation(marketingParam.getCreateBy(), marketing);
		return message.setData(marketingResponseVO);
	}

	@Override
	public ResponseMessage queryMarketingDetailNoCheckById(MarketingParam marketingParam) {
		// 卡，券信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingParam.getId(), marketingParam.getMarketingType());
		if (marketing == null) {
			return ResponseMessage.error("该卡券无效", 500);
		}
		MarketingResponseVo marketingResponseVO = new MarketingResponseVo();
		BeanUtils.copyProperties(marketing, marketingResponseVO);
		if(StringUtils.isNotBlank(marketingResponseVO.getStoreIds())) {
			String storeIds = marketingResponseVO.getStoreIds();
			if(storeIds.startsWith("0,")) {
				storeIds = storeIds.substring(2, storeIds.length());
			}
			if(storeIds.endsWith(",0")) {
				storeIds = storeIds.substring(0, storeIds.length()-2);
			}
			marketingResponseVO.setStoreIds(storeIds);
		}
		StringBuffer daysInfo = new StringBuffer();
		if(StringUtils.isNotBlank(marketing.getWeekHourIds()) 
				&& (!marketing.getWeekHourIds().equals("0"))) {
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(marketing.getId()).andStatusEqualTo(Constant.STATUS_YES)
					.andActivityTypeEqualTo(marketing.getMarketingType());
			example.setOrderByClause(" dayids desc");
			// 卡券活动时间
			List<TActivityDays> days = tActivityDaysMapper.selectByExample(example);
			List<ActivityDaysResponseVo> daysVo = new ArrayList<ActivityDaysResponseVo>();
			for (TActivityDays day : days) {
				ActivityDaysResponseVo activityDaysResponseVo = new ActivityDaysResponseVo();
				BeanUtils.copyProperties(day, activityDaysResponseVo);
				daysVo.add(activityDaysResponseVo);
				String daysIds = day.getDayids();
				if (daysIds.startsWith(",")) {
					daysIds = daysIds.substring(1, daysIds.length());
				}
				if (daysIds.endsWith(",")) {
					daysIds = daysIds.substring(0, daysIds.length() - 1);
				}
				daysInfo.append(WeekUtil.convertWeek(daysIds)).append(", ")
						.append(DateUtils.formatDate(day.getStartTime(), DateUtils.TIME_FORMAT)).append("-")
						.append(DateUtils.formatDate(day.getEndTime(), DateUtils.TIME_FORMAT)).append("; ");
			}
			// 卡券添加活动时间
			marketingResponseVO.setActivityDays(daysVo);
		}
		if(StringUtils.isBlank(daysInfo.toString())){
			daysInfo.append("0:00-24:00");
		}
		marketingResponseVO.setDayMemo(daysInfo.toString());
		// 领取规则验证
		return ResponseMessage.ok(marketingResponseVO);
	}
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage bindReceiveAccount(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		// 卡，券信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingReceiveHistoryParam.getMarketingId(),
				marketingReceiveHistoryParam.getMarketingType());
		if (marketing == null) {
			return ResponseMessage.error("查询券(卡)无数据", 500);
		}
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			return ResponseMessage.error("券类型不合法", 500);
		}
		// 领取规则验证
		ResponseMessage message = marketingRuleReceiveValidation(marketingReceiveHistoryParam.getCreateBy(), marketing);
		if (message.getStatus() != ResponseMessage.ok().getStatus()) {
			return message;
		}
		// 构建领取记录
		TMarketingReceiveHistory history = null;
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
			history = new TMarketingReceiveHistoryCoupon();
			buildNewReceiveHistory(marketingReceiveHistoryParam, marketing, null, history);
			tMarketingReceiveHistoryCouponMapper.insertSelective((TMarketingReceiveHistoryCoupon) history);
		} else if (marketing.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()) {
			history = new TMarketingReceiveHistoryCardWithBLOBs();
			buildNewReceiveHistory(marketingReceiveHistoryParam, marketing, null, history);
			tMarketingReceiveHistoryCardMapper.insertSelective((TMarketingReceiveHistoryCardWithBLOBs) history);
		} else if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			history = new TMarketingReceiveHistoryCouponBag();
			buildNewReceiveHistory(marketingReceiveHistoryParam, marketing, null, history);
			tMarketingReceiveHistoryCouponBagMapper.insertSelective((TMarketingReceiveHistoryCouponBag) history);
		}
		// 券,卡库存新增变更记录
		String memo = "更新" + MarketingTypeEnum.parseStatus(marketing.getMarketingType()).getDesc() + ",用户领取变更库存";
		inventoryService.addInventoryModificationRecord(marketing.getId(), history.getId(), 1, memo,
				marketingReceiveHistoryParam.getCreateBy(), marketing.getMarketingType());
		return ResponseMessage.ok(history).setmsg("领取成功");
	}

	private void buildNewReceiveHistory(MarketingReceiveHistoryParam marketingReceiveHistoryParam, TMarketing marketing,
			Long marketingBagId, TMarketingReceiveHistory history) {
		buildNewReceiveHistory(marketingReceiveHistoryParam, marketing, marketingBagId, history, null);
	}

	private void buildNewReceiveHistory(MarketingReceiveHistoryParam marketingReceiveHistoryParam, TMarketing marketing,
			Long marketingBagId, TMarketingReceiveHistory history, String receiveNo) {
		// 构建用户领取信息
		if (marketingReceiveHistoryParam != null) {
			BeanUtils.copyProperties(marketingReceiveHistoryParam, history);
			history.setUserId(marketingReceiveHistoryParam.getCreateBy());
			history.setRedeemCode(marketingReceiveHistoryParam.getRedeemCode());
		}
		history.setMarketingId(marketing.getId());
		history.setMarketingBagId(marketingBagId);
		history.setMarketingName(marketing.getName());
		history.setReceiveNo(receiveNo);
		history.setRefundType(marketing.getRefundType());
		if (StringUtils.isBlank(receiveNo)) {
			String random = commonService.getOnlyRandomNo(RedisKeyEnum.RECEIVE_ONLY_KEY.getKeyName(DateUtils.getDate()),
					(marketing.getMarketingType() + 1) + "");
			history.setReceiveNo(random);
		}
		history.setMarketingType(marketing.getMarketingType());
		history.setServiceType(marketing.getServiceType());
		history.setLeastCost(marketing.getLeastCost());
		history.setCouponAmount(marketing.getCouponAmount());
		if (marketing.getMarketingType().intValue() != MarketingTypeEnum.COUPON_BAG.getCode()
				&& marketing.getUseType() == 0) {// 相对时间
			history.setUseStartTime(DateUtils.getCurdate());
			Date endDate = DateUtils.addSomeDays(history.getUseStartTime(), marketing.getUsePeriod());
			history.setUseEndTime(DateUtils.addSeconds(endDate, -1));
		} else if (marketing.getMarketingType().intValue() != MarketingTypeEnum.COUPON_BAG.getCode()
				&& marketing.getUseType() == 1) {// 指定时间
			history.setUseStartTime(marketing.getUseStartTime());
			Date endDate = DateUtils.addSomeDays(DateUtils.getCurdate(marketing.getUseEndTime()), 1);
			history.setUseEndTime(DateUtils.addSeconds(endDate, -1));
		}
		history.setInitUseLimit(marketing.getUseLimitTotal());
		if(marketing.getMarketingType().equals(MarketingTypeEnum.COUPON.getCode())) {
			history.setInitUseLimit(1);
		}
		history.setCurrentUseLimit(0);
		history.setWeekHourIds(marketing.getWeekHourIds());
		history.setStatus(MarketingReceiveStatusEnum.AVAILABLE.getCode());
		history.setCreateTime(new Date());
		if (marketing.getMarketingType().equals(MarketingTypeEnum.CARD.getCode())
				&& marketing.getServiceType().equalsIgnoreCase(MarketingServiceTypeEnum.FREE.getType())) {
			history.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
		} else {
			history.setAuthStatus(AuthStatusEnum.AUTHENTICATED.getCode());
			
		}
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			history.setCouponBagType(marketing.getCouponBagType());
		}
	}

	private ResponseMessage marketingRuleReceiveValidation(Long userId, TMarketing marketing) {
		if (marketing == null) {
			return ResponseMessage.error("抱歉，未查询到优惠活动,请您关注其他优惠活动", -1);
		}
		if (marketing.getStockQuantity().intValue() != 0 && marketing.getSurplusQuantity().intValue() <= 0) {
			return ResponseMessage.error("抱歉，您慢了一步！优惠已被抢完啦，请您关注其他优惠活动", -3);
		}
		if (marketing.getReceiveStartTime().after(new Date())) {
			return ResponseMessage.error("抱歉，此活动尚未开始 请您耐心等待 优惠开始时间"
					+ DateUtils.formatDate(marketing.getReceiveStartTime(), DateUtils.DATE_FORMAT), 0);
		}
		if (marketing.getReceiveEndTime().before(new Date())) {
			return ResponseMessage.error("抱歉，此优惠活动已结束,请您关注其他优惠活动", -2);
		}

		if (MarketingStatusEnum.UP.getCode() != marketing.getStatus().intValue()) {
			return ResponseMessage.error("抱歉，此优惠活动已结束,请您关注其他优惠活动", -2);
		}
		if (userId != null
				&& MarketingReceiveTypeEnum.PLATFORM_NEW.getCode() == marketing.getReceiveType().intValue()) {
			Integer userType = userService.verifyIsNewUser(userId);
			if (userType.intValue() == 0) {
				return ResponseMessage.error("抱歉，您无法参与此优惠。此优惠仅限星客多新用户领取", -1);
			}
		}
		// 单日每人领取上限
		if (userId != null && marketing.getGetLimitDay() != null && marketing.getGetLimitDay().intValue() != 0) {
			Date startDate = DateUtils.getCurdate();
			Date endDate = DateUtils.addSomeDays(startDate, 1);
			int count = countReceiveHistoryByUserId(userId, marketing.getId(), marketing.getMarketingType(), startDate,
					endDate);
			if (count >= marketing.getGetLimitDay()) {
				return ResponseMessage.error("抱歉，您已经领取该优惠。此优惠每位用户每日仅限领取" + marketing.getGetLimitDay() + "次", 1);
			}
		}
		// 累计领取上限
		if (userId != null && marketing.getGetLimitTotal() != null && marketing.getGetLimitTotal().intValue() != 0) {
			int count = countReceiveHistoryByUserId(userId, marketing.getId(), marketing.getMarketingType(), null,
					null);
			if (count >= marketing.getGetLimitTotal()) {
				return ResponseMessage.error("抱歉，您已经领取该优惠。此优惠每位用户仅限领取" + marketing.getGetLimitTotal() + "次", 1);
			}
		}
		//banner领取需验证用户是barber新用户
		if(userId != null 
				&& marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
			List<TDictMarketing> dictList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(DictMarketingEnum.BANNER_BARBER_RECEIVE.name(), marketing.getId().toString());
			if(!CollectionUtils.isEmpty(dictList)) {
				List<Long> userIds = userService.queryUserIdsByUserId(userId);
				for(TDictMarketing dictMarketing : dictList) {
					TMarketingReceiveHistoryCouponExample example = new TMarketingReceiveHistoryCouponExample();
					example.createCriteria()
						   .andUserIdIn(userIds)
						   .andStatusIn(Lists.newArrayList(Constant.STATUS_YES,Constant.STATUS_NO_2))
						   .andUseEndTimeGreaterThanOrEqualTo(new Date())
						   .andMarketingIdIn(Arrays.asList(dictMarketing.getItemValue().split(",")).stream().filter(item->StringUtils.isNotBlank(item)).map(itemValue -> Long.parseLong(itemValue.trim())).collect(Collectors.toList()));
					if(tMarketingReceiveHistoryCouponMapper.countByExample(example)>0) {
						return ResponseMessage.error("抱歉，您已经领取该优惠。此优惠每位用户仅限领取1次", 1);
					}
				}
			}
		}
		// 券包情况下，需额外验证卡券是否上架
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			TMarketingRelevantExample tMarketingRelevantExample = new TMarketingRelevantExample();
			tMarketingRelevantExample.createCriteria()
									 .andMarketingIdEqualTo(marketing.getId())
									 .andStatusEqualTo(Constant.STATUS_YES)
									 .andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> historyList = tMarketingRelevantMapper.selectByExample(tMarketingRelevantExample);
			if (CollectionUtils.isEmpty(historyList)) {
				logger.info("【优惠包领取】券包下没有查询包含到关联卡，券信息");
				return ResponseMessage.error("抱歉，此优惠活动已结束,请您关注其他优惠活动", -2);
			}
			for (TMarketingRelevant relevant : historyList) {
				TMarketing oldmarketing = marketingService.selectMarketingByPrimaryKey(relevant.getSupportBusinessId(),
						relevant.getMarketingType());
				if (oldmarketing == null) {
					logger.info("【优惠包领取】券包下没有查询对应的卡，券信息");
					return ResponseMessage.error("抱歉，此优惠活动已结束,请您关注其他优惠活动", -2);
				}
				if (MarketingStatusEnum.UP.getCode() != oldmarketing.getStatus().intValue()) {
					logger.info("【优惠包领取】券包下查询到有券，卡未上架");
					return ResponseMessage.error("抱歉，此优惠活动已结束,请您关注其他优惠活动", -2);
				}
			}
		}
		return ResponseMessage.ok().setmsg("使用规则验证成功");
	}

	private int countReceiveHistoryByUserId(Long userId, Long marketingId, Integer marketingType, Date startDate,
			Date endDate) {
		List<Long> userIds = userService.queryUserIdsByUserId(userId);
		if (marketingType.intValue() == MarketingTypeEnum.COUPON.getCode()) {
			TMarketingReceiveHistoryCouponExample example = new TMarketingReceiveHistoryCouponExample();
			TMarketingReceiveHistoryCouponExample.Criteria criteria = example.createCriteria();
			criteria.andUserIdIn(userIds);
			if (marketingId != null) {
				criteria.andMarketingIdEqualTo(marketingId);
			}
			if (startDate != null) {
				criteria.andCreateTimeGreaterThanOrEqualTo(startDate);
			}
			if (endDate != null) {
				criteria.andCreateTimeLessThanOrEqualTo(endDate);
			}
			return tMarketingReceiveHistoryCouponMapper.countByExample(example);
		} else if (marketingType.intValue() == MarketingTypeEnum.CARD.getCode()) {
			TMarketingReceiveHistoryCardExample example = new TMarketingReceiveHistoryCardExample();
			TMarketingReceiveHistoryCardExample.Criteria criteria = example.createCriteria();
			criteria.andUserIdIn(userIds);
			if (marketingId != null) {
				criteria.andMarketingIdEqualTo(marketingId);
			}
			if (startDate != null) {
				criteria.andCreateTimeGreaterThanOrEqualTo(startDate);
			}
			if (endDate != null) {
				criteria.andCreateTimeLessThanOrEqualTo(endDate);
			}
			return tMarketingReceiveHistoryCardMapper.countByExample(example);
		} else if (marketingType.intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			TMarketingReceiveHistoryCouponBagExample example = new TMarketingReceiveHistoryCouponBagExample();
			TMarketingReceiveHistoryCouponBagExample.Criteria criteria = example.createCriteria();
			criteria.andUserIdIn(userIds);
			if (marketingId != null) {
				criteria.andMarketingBagIdEqualTo(marketingId);
			}
			if (startDate != null) {
				criteria.andCreateTimeGreaterThanOrEqualTo(startDate);
			}
			if (endDate != null) {
				criteria.andCreateTimeLessThanOrEqualTo(endDate);
			}
			return tMarketingReceiveHistoryCouponBagMapper.countByExample(example);
		}
		return 0;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage bindBagReceiveAccount(String code, Long userId) {
		// 兑换码验证是否可用
		TActivityCodeExample example = new TActivityCodeExample();
		example.createCriteria().andCodeEqualTo(code);
		List<TActivityCode> activityCodeList = tActivityCodeMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(activityCodeList)) {
			return ResponseMessage.error("兑换码无效", 500);
		}
		if (activityCodeList.size() > 1) {
			return ResponseMessage.error("兑换码无效", 500);
		}
		TActivityCode activityCode = activityCodeList.get(0);
		ActivityCodeStatusEnum activityCodeStatusEnum = ActivityCodeStatusEnum.parseStatus(activityCode.getStatus());
		if (activityCodeStatusEnum.getCode() != ActivityCodeStatusEnum.EFFECTIVE.getCode()) {
			return ResponseMessage.error("兑换码" + activityCodeStatusEnum.getDesc(), 500);
		}
		// 券包信息
		TMarketing marketing = null;
		if (activityCode.getMarketingId() != null) {
			marketing = marketingService.selectMarketingByPrimaryKey(activityCode.getMarketingId(),
					MarketingTypeEnum.COUPON_BAG.getCode());
		} else if (StringUtils.isNotBlank(activityCode.getItemId())) {
			TMarketingCouponBagExample marketingExample = new TMarketingCouponBagExample();
			marketingExample.createCriteria().andThirdBizIdEqualTo(activityCode.getItemId());
			List<TMarketingCouponBag> marketingList = tMarketingCouponBagMapper.selectByExample(marketingExample);
			if (CollectionUtils.isEmpty(marketingList)) {
				return ResponseMessage.error("套餐id无效", 500);
			}
			if (marketingList.size() > 1) {
				return ResponseMessage.error("套餐id无效", 500);
			}
			if (!CollectionUtils.isEmpty(marketingList)) {
				marketing = marketingList.get(0);
			}
		}
		if (marketing == null) {
			return ResponseMessage.error("兑换码无效", 500);
		}
		// 领取规则验证
		ResponseMessage message = marketingRuleReceiveValidation(userId, marketing);
		if (message.getStatus() != ResponseMessage.ok().getStatus()) {
			return message;
		}
		// 兑换码失效处理
		TActivityCode record = new TActivityCode();
		record.setId(activityCode.getId());
		record.setUserId(userId);
		record.setConvertTime(new Date());
		record.setStatus(ActivityCodeStatusEnum.USED.getCode());
		record.setUpdateTime(new Date());
		tActivityCodeMapper.updateByPrimaryKeySelective(record);

		VerifyReedRedeemCodeParam param = new VerifyReedRedeemCodeParam();
		param.setF_number("1");
		param.setF_type(marketing.getCouponBagType().toString());// 自有券
		param.setF_checktime(DateUtils.getDate(DateUtils.DEFAULT_DATE_TIME_FORMAT));
		param.setF_createtime(DateUtils.getDate(DateUtils.DEFAULT_DATE_TIME_FORMAT));
		param.setF_status(Constant.STATUS_YES.toString());
		param.setF_code(code);
		param.setF_channel("2");
		param.setF_sub_type("1");
		param.setF_coupon_bag_id(activityCode.getMarketingId().toString());
		param.setF_user_id(userId.toString());
		param.setF_coupon_detail_ids(marketing.getSupportMarketingIds());
		this.saveUserPurchaseRecord(param);
		// 生成券包下支持的券卡数据;
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			// 构建券包领取记录
			MarketingReceiveHistoryParam marketingReceiveHistoryParamBag = new MarketingReceiveHistoryParam();
			marketingReceiveHistoryParamBag.setRedeemCode(code);
			marketingReceiveHistoryParamBag.setCreateBy(userId);
			marketingReceiveHistoryParamBag.setSendType(MarketingReceiveSendTypeEnum.REDEEM_CODE.getCode());
			TMarketingReceiveHistory bagHistory = new TMarketingReceiveHistoryCouponBag();
			buildNewReceiveHistory(marketingReceiveHistoryParamBag, marketing, marketing.getId(), bagHistory);
			tMarketingReceiveHistoryCouponBagMapper.insertSelective((TMarketingReceiveHistoryCouponBag) bagHistory);
			// 前端渲染数据-券包下券，卡数据
			List<MarketingValuePackResponseVo> resultList = new ArrayList<MarketingValuePackResponseVo>();
			// 根据关联关系查询券包下券，卡数据
			TMarketingRelevantExample tMarketingRelevantExample = new TMarketingRelevantExample();
			tMarketingRelevantExample.createCriteria()
								     .andMarketingIdEqualTo(marketing.getId())
								     .andStatusEqualTo(Constant.STATUS_YES)
								     .andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> relevantList = tMarketingRelevantMapper.selectByExample(tMarketingRelevantExample);
			for (TMarketingRelevant marketingRelevant : relevantList) {
				// 查询具体的券信息
				TMarketing subMarketing = marketingService.selectMarketingByPrimaryKey(marketingRelevant.getSupportBusinessId(),
						marketingRelevant.getMarketingType());
				int count = marketingRelevant.getTotalQuantity();
				for (int i = 0; i < count; i++) {
					// 构建领取记录
					MarketingReceiveHistoryParam marketingReceiveHistoryParam = new MarketingReceiveHistoryParam();
					marketingReceiveHistoryParam.setRedeemCode(code);
					marketingReceiveHistoryParam.setCreateBy(userId);
					marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.COUPON_BAG.getCode());
					TMarketingReceiveHistory history = null;
					if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
						history = new TMarketingReceiveHistoryCoupon();
						buildNewReceiveHistory(marketingReceiveHistoryParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCouponMapper.insertSelective((TMarketingReceiveHistoryCoupon) history);
					} else if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()) {
						history = new TMarketingReceiveHistoryCardWithBLOBs();
						buildNewReceiveHistory(marketingReceiveHistoryParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCardMapper
								.insertSelective((TMarketingReceiveHistoryCardWithBLOBs) history);
					} else if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
						history = new TMarketingReceiveHistoryCouponBag();
						buildNewReceiveHistory(marketingReceiveHistoryParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCouponBagMapper
								.insertSelective((TMarketingReceiveHistoryCouponBag) history);
					}
				}
				// 构建返回前端数据
				MarketingValuePackResponseVo valuePack = new MarketingValuePackResponseVo();
				BeanUtils.copyProperties(subMarketing, valuePack);
				valuePack.setTotalQuantity(marketingRelevant.getTotalQuantity());
				resultList.add(valuePack);
			}
			// 券,卡库存新增变更记录
			String memo = "更新优惠包,用户领取变更库存";
			inventoryService.addInventoryModificationRecord(marketing.getId(), bagHistory.getId(), 1, memo, userId,
					marketing.getMarketingType());
			return ResponseMessage.ok(resultList);
		}
		return ResponseMessage.ok("兑换码兑换成功");
	}

	@Override
	public ResponseMessage queryCouponBagDetailById(MarketingParam marketingParam) {
		// 券包信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingParam.getId(), marketingParam.getMarketingType());
		MarketingResponseVo marketingResponseVO = new MarketingResponseVo();
		BeanUtils.copyProperties(marketing, marketingResponseVO);
		if (marketing.getMarketingType().intValue() != MarketingTypeEnum.COUPON_BAG.getCode()) {
			return ResponseMessage.ok(marketingResponseVO);
		}
		TMarketingRelevantExample example = new TMarketingRelevantExample();
		example.createCriteria()
			   .andMarketingIdEqualTo(marketing.getId())
			   .andStatusEqualTo(Constant.STATUS_YES)
			   .andTotalQuantityGreaterThan(0);
		example.setOrderByClause(" id desc");
		// 券包-关联卡券
		List<TMarketingRelevant> relevant = tMarketingRelevantMapper.selectByExample(example);
		marketingResponseVO.setMarketingRelevants(relevant);
		// 领取规则验证
		ResponseMessage message = marketingRuleReceiveValidation(marketingParam.getCreateBy(), marketing);
		return message.setData(marketingResponseVO);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage bindBagReceiveAccount(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		// 券包信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingReceiveHistoryParam.getMarketingId(),
				marketingReceiveHistoryParam.getMarketingType());
		// 领取规则验证
		if(marketingReceiveHistoryParam.getCheckFlag()) {
			logger.info("开启验证券规则");
			ResponseMessage message = marketingRuleReceiveValidation(marketingReceiveHistoryParam.getCreateBy(), marketing);
			if (message.getStatus() != ResponseMessage.ok().getStatus()) {
				return message;
			}
		}
		// 生成券包下支持的券卡数据;
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			// 构建券包领取记录
			MarketingReceiveHistoryParam marketingReceiveHistoryParamBag = new MarketingReceiveHistoryParam();
			marketingReceiveHistoryParamBag.setCreateBy(marketingReceiveHistoryParam.getCreateBy());
			marketingReceiveHistoryParamBag.setSendType(marketingReceiveHistoryParam.getSendType());
			TMarketingReceiveHistory bagHistory = new TMarketingReceiveHistoryCouponBag();
			buildNewReceiveHistory(marketingReceiveHistoryParamBag, marketing, marketing.getId(), bagHistory);
			tMarketingReceiveHistoryCouponBagMapper.insertSelective((TMarketingReceiveHistoryCouponBag) bagHistory);
			// 前端渲染数据-券包下券，卡数据
			List<MarketingValuePackResponseVo> resultList = new ArrayList<MarketingValuePackResponseVo>();
			// 根据关联关系查询券包下券，卡数据
			TMarketingRelevantExample tMarketingRelevantExample = new TMarketingRelevantExample();
			tMarketingRelevantExample.createCriteria()
			 						 .andMarketingIdEqualTo(marketing.getId())
			 						 .andStatusEqualTo(Constant.STATUS_YES)
								     .andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> relevantList = tMarketingRelevantMapper.selectByExample(tMarketingRelevantExample);
			for (TMarketingRelevant marketingRelevant : relevantList) {
				// 查询具体的券信息
				TMarketing subMarketing = marketingService.selectMarketingByPrimaryKey(marketingRelevant.getSupportBusinessId(),
						marketingRelevant.getMarketingType());
				int count = marketingRelevant.getTotalQuantity();
				for (int i = 0; i < count; i++) {
					// 构建领取记录
					MarketingReceiveHistoryParam historyParam = new MarketingReceiveHistoryParam();
					historyParam.setCreateBy(marketingReceiveHistoryParam.getCreateBy());
					historyParam.setSendType(MarketingReceiveSendTypeEnum.COUPON_BAG.getCode());
					TMarketingReceiveHistory history = null;
					if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
						history = new TMarketingReceiveHistoryCoupon();
						buildNewReceiveHistory(historyParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCouponMapper.insertSelective((TMarketingReceiveHistoryCoupon) history);
					} else if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()) {
						history = new TMarketingReceiveHistoryCardWithBLOBs();
						buildNewReceiveHistory(historyParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCardMapper
								.insertSelective((TMarketingReceiveHistoryCardWithBLOBs) history);
					} else if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
						history = new TMarketingReceiveHistoryCouponBag();
						buildNewReceiveHistory(historyParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCouponBagMapper
								.insertSelective((TMarketingReceiveHistoryCouponBag) history);
					}
				}
				// 构建返回前端数据
				MarketingValuePackResponseVo valuePack = new MarketingValuePackResponseVo();
				BeanUtils.copyProperties(subMarketing, valuePack);
				valuePack.setTotalQuantity(marketingRelevant.getTotalQuantity());
				resultList.add(valuePack);
			}
			// 券,卡库存新增变更记录
			String memo = "更新优惠包,用户领取变更库存";
			inventoryService.addInventoryModificationRecord(marketing.getId(), bagHistory.getId(), 1, memo,
					marketingReceiveHistoryParam.getCreateBy(), marketing.getMarketingType());
			return ResponseMessage.ok(resultList);
		}
		return ResponseMessage.ok("券包领取成功");
	}

	@Override
	public ResponseMessage saveUserPurchaseRecord(VerifyReedRedeemCodeParam verifyReedRedeemCodeParam) {
		TService record = new TService();
		buildServiceRecord(record, verifyReedRedeemCodeParam);
		if (record.getfCouponBagId() == null) {
			return ResponseMessage.error("匹配不到券信息", 500);
		}
	    tServiceMapper.insertSelective(record);
		return ResponseMessage.ok(record);
	}

	private void buildServiceRecord(TService record, VerifyReedRedeemCodeParam verifyReedRedeemCodeParam) {
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_admin_id())) {
			record.setfAdminId(Long.parseLong(verifyReedRedeemCodeParam.getF_admin_id()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_store_id())) {
			record.setfStoreId(Long.parseLong(verifyReedRedeemCodeParam.getF_store_id()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_number())) {
			record.setfNumber(Integer.parseInt(verifyReedRedeemCodeParam.getF_number()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_price())) {
			record.setfPrice(new BigDecimal(verifyReedRedeemCodeParam.getF_price()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_order_no())) {
			record.setfOrderNo(verifyReedRedeemCodeParam.getF_order_no());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_type())) {
			record.setfType(Integer.parseInt(verifyReedRedeemCodeParam.getF_type()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_checktime())) {
			record.setfChecktime(DateUtils.parseDate(verifyReedRedeemCodeParam.getF_checktime()));
		}else {
			record.setfChecktime(new Date());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_createtime())) {
			record.setfCreatetime(DateUtils.parseDate(verifyReedRedeemCodeParam.getF_createtime()));
		}else {
			record.setfCreatetime(new Date());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_pic())) {
			record.setfPic(verifyReedRedeemCodeParam.getF_pic());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_pic_dir())) {
			record.setfPicDir(verifyReedRedeemCodeParam.getF_pic_dir());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_code())) {
			record.setfCode(verifyReedRedeemCodeParam.getF_code());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_status())) {
			record.setfStatus(Integer.parseInt(verifyReedRedeemCodeParam.getF_status()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_check_admin_id())) {
			record.setfCheckAdminId(Long.parseLong(verifyReedRedeemCodeParam.getF_check_admin_id()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_row_no())) {
			record.setfRowNo(Integer.parseInt(verifyReedRedeemCodeParam.getF_row_no()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_channel())) {
			record.setfChannel(Integer.parseInt(verifyReedRedeemCodeParam.getF_channel()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_koubei_order_no())) {
			record.setfKoubeiOrderNo(verifyReedRedeemCodeParam.getF_koubei_order_no());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_koubei_item_id())) {
			record.setfKoubeiItemId(verifyReedRedeemCodeParam.getF_koubei_item_id());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_sub_type())) {
			record.setfSubType(Integer.parseInt(verifyReedRedeemCodeParam.getF_sub_type()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_coupon_bag_id())) {
			record.setfCouponBagId(Long.parseLong(verifyReedRedeemCodeParam.getF_coupon_bag_id()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_user_id())) {
			record.setfUserId(Long.parseLong(verifyReedRedeemCodeParam.getF_user_id()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_coupon_detail_ids())) {
			record.setfCouponDetailIds(verifyReedRedeemCodeParam.getF_coupon_detail_ids());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_remark())) {
			record.setfRemark(verifyReedRedeemCodeParam.getF_remark());
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_market_price())) {
			record.setfMarketPrice(new BigDecimal(verifyReedRedeemCodeParam.getF_market_price()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_selling_price())) {
			record.setfSellingPrice(new BigDecimal(verifyReedRedeemCodeParam.getF_selling_price()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_payment_price())) {
			record.setfPaymentPrice(new BigDecimal(verifyReedRedeemCodeParam.getF_payment_price()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_subsidies_price())) {
			record.setfSubsidiesPrice(new BigDecimal(verifyReedRedeemCodeParam.getF_subsidies_price()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_platform_pay_price())) {
			record.setfPlatformPayPrice(new BigDecimal(verifyReedRedeemCodeParam.getF_platform_pay_price()));
		}
		if (StringUtils.isNotBlank(verifyReedRedeemCodeParam.getF_third_store_id())) {
			record.setfThirdStoreId(Long.parseLong(verifyReedRedeemCodeParam.getF_third_store_id()));
		}
		if (StringUtils.isNotBlank(record.getfKoubeiItemId()) && record.getfCouponBagId() == null) {
			TMarketingCouponBagExample example = new TMarketingCouponBagExample();
			example.createCriteria().andThirdBizIdEqualTo(record.getfKoubeiItemId())
					.andStatusEqualTo(Constant.STATUS_YES);
			List<TMarketingCouponBag> marketingList = tMarketingCouponBagMapper.selectByExample(example);
			if (CollectionUtils.isEmpty(marketingList)) {
				throw new RuntimeException("查询优惠包信息为空");
			}
			if (marketingList.size() > 1) {
				throw new RuntimeException("查询优惠包信息不唯一");
			}
			if (marketingList.size() == 1) {
				record.setfCouponBagId(marketingList.get(0).getId());
				record.setfCouponDetailIds(marketingList.get(0).getSupportMarketingIds());
			}
		}
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage bindUserPurchaseRedeemCode(String redeemCodeId, String marketingId) throws Exception {
		// 兑换码验证是否可用
		TService record = new TService();
		record.setfStatus(Constant.STATUS_YES);
		record.setfChecktime(new Date());
		TServiceExample example = new TServiceExample();
		example.createCriteria().andFIdEqualTo(Long.parseLong(redeemCodeId))
				.andFCouponBagIdEqualTo(Long.parseLong(marketingId)).andFStatusEqualTo(Constant.STATUS_NO);
		int serviceCount = tServiceMapper.updateByExampleSelective(record, example);
		if (serviceCount != 1) {
			throw new RuntimeException("核销信息不合法");
		}
		TService newService = tServiceMapper.selectByPrimaryKey(Long.parseLong(redeemCodeId));
		// 券包信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(Long.parseLong(marketingId),
				MarketingTypeEnum.COUPON_BAG.getCode());
		// 领取规则验证
		ResponseMessage message = marketingRuleReceiveValidation(newService.getfUserId(), marketing);
		if (message.getStatus() != ResponseMessage.ok().getStatus()) {
			return message;
		}
		// 生成券包下支持的券卡数据;
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			// 构建券包领取记录
			MarketingReceiveHistoryParam marketingReceiveHistoryParamBag = new MarketingReceiveHistoryParam();
			marketingReceiveHistoryParamBag.setRedeemCode(newService.getfCode());
			marketingReceiveHistoryParamBag.setCreateBy(newService.getfUserId());
			marketingReceiveHistoryParamBag.setStoreId(newService.getfStoreId());
			marketingReceiveHistoryParamBag.setStoreName(newService.getfRemark());
			marketingReceiveHistoryParamBag.setSendType(MarketingReceiveSendTypeEnum.MEI_TUAN.getCode());// 美团
			if (marketing.getCouponBagType() == MarketingCouponBagTypeEnum.WORD_OF_MOUTH.getCode()) {
				marketingReceiveHistoryParamBag.setSendType(MarketingReceiveSendTypeEnum.KOU_BEI.getCode());// 口碑
			}
			TMarketingReceiveHistory bagHistory = new TMarketingReceiveHistoryCouponBag();
			buildNewReceiveHistory(marketingReceiveHistoryParamBag, marketing, marketing.getId(), bagHistory);
			tMarketingReceiveHistoryCouponBagMapper.insertSelective((TMarketingReceiveHistoryCouponBag) bagHistory);
			// 前端渲染数据-券包下券，卡数据
			List<MarketingValuePackResponseVo> resultList = new ArrayList<MarketingValuePackResponseVo>();
			// 根据关联关系查询券包下券，卡数据
			TMarketingRelevantExample tMarketingRelevantExample = new TMarketingRelevantExample();
			tMarketingRelevantExample.createCriteria()
									 .andMarketingIdEqualTo(marketing.getId())
									 .andStatusEqualTo(Constant.STATUS_YES)
								     .andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> relevantList = tMarketingRelevantMapper.selectByExample(tMarketingRelevantExample);
			for (TMarketingRelevant marketingRelevant : relevantList) {
				// 查询具体的券信息
				TMarketing subMarketing = marketingService.selectMarketingByPrimaryKey(marketingRelevant.getSupportBusinessId(),
						marketingRelevant.getMarketingType());
				int count = marketingRelevant.getTotalQuantity();
				for (int i = 0; i < count; i++) {
					// 构建领取记录
					MarketingReceiveHistoryParam marketingReceiveHistoryParam = new MarketingReceiveHistoryParam();
					marketingReceiveHistoryParam.setRedeemCode(newService.getfCode());
					marketingReceiveHistoryParam.setCreateBy(newService.getfUserId());
					marketingReceiveHistoryParam.setStoreId(newService.getfStoreId());
					marketingReceiveHistoryParam.setStoreName(newService.getfRemark());
					marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.COUPON_BAG.getCode());
					TMarketingReceiveHistory history = null;
					if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
						history = new TMarketingReceiveHistoryCoupon();
						buildNewReceiveHistory(marketingReceiveHistoryParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCouponMapper.insertSelective((TMarketingReceiveHistoryCoupon) history);
					} else if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()) {
						history = new TMarketingReceiveHistoryCardWithBLOBs();
						buildNewReceiveHistory(marketingReceiveHistoryParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCardMapper
								.insertSelective((TMarketingReceiveHistoryCardWithBLOBs) history);
					} else if (subMarketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
						history = new TMarketingReceiveHistoryCouponBag();
						buildNewReceiveHistory(marketingReceiveHistoryParam, subMarketing, marketing.getId(), history,
								bagHistory.getReceiveNo());
						history.setMarketingBagReceiveHistoryId(bagHistory.getId());
						tMarketingReceiveHistoryCouponBagMapper
								.insertSelective((TMarketingReceiveHistoryCouponBag) history);
					}
				}
				// 构建返回前端数据
				MarketingValuePackResponseVo valuePack = new MarketingValuePackResponseVo();
				BeanUtils.copyProperties(subMarketing, valuePack);
				valuePack.setTotalQuantity(marketingRelevant.getTotalQuantity());
				resultList.add(valuePack);
			}
			// 券,卡库存新增变更记录
			String memo = "更新优惠包,用户领取变更库存";
			inventoryService.addInventoryModificationRecord(marketing.getId(), bagHistory.getId(), 1, memo,
					newService.getfUserId(), marketing.getMarketingType());
			return ResponseMessage.ok(resultList);
		}
		return ResponseMessage.ok("兑换码兑换成功");
	}

	@Override
	public ResponseMessage queryMarketingBagByRedeemCode(String code) {
		TServiceExample example = new TServiceExample();
		example.createCriteria().andFCodeEqualTo(code);
		List<TService> serviceList = tServiceMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(serviceList)) {
			return ResponseMessage.error("核销数据查询失败", 500);
		}
		for (TService tService : serviceList) {
			TMarketing marketing = marketingService.selectMarketingByPrimaryKey(tService.getfCouponBagId(),
					MarketingTypeEnum.COUPON_BAG.getCode());
			TMarketingRelevantExample tMarketingRelevantExample = new TMarketingRelevantExample();
			tMarketingRelevantExample.createCriteria()
									 .andMarketingIdEqualTo(marketing.getId())
									 .andStatusEqualTo(Constant.STATUS_YES)
								     .andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> historyList = tMarketingRelevantMapper.selectByExample(tMarketingRelevantExample);
			List<MarketingResponseVo> marketingResponseList = new ArrayList<>();
			for (TMarketingRelevant relevant : historyList) {
				TMarketing relevantMarketing = marketingService.selectMarketingByPrimaryKey(relevant.getSupportBusinessId(),
						relevant.getMarketingType());
				MarketingResponseVo responseVo = new MarketingResponseVo();
				BeanUtils.copyProperties(relevantMarketing, responseVo);
				responseVo.setTotalQuantity(relevant.getTotalQuantity());
				marketingResponseList.add(responseVo);
			}
			tService.setCoupon_bag(marketingResponseList);
		}
		return ResponseMessage.ok(serviceList.get(0));
	}

	public ResponseMessage queryMarketingBagSurplusQuantityByItemId(String itemId) {
		MarketingParam marketingParam = new MarketingParam();
		marketingParam.setMarketingType(MarketingTypeEnum.COUPON_BAG.getCode());
		marketingParam.setThirdBizId(itemId);
		ResponseMessage result = queryCouponBagDetailByItemId(marketingParam);
		if (result == null) {
			return ResponseMessage.error("查询失败", 500);
		}
		if (result.getStatus() != ResponseMessage.ok().getStatus()) {
			return result;
		}
		MarketingResponseVo marketingResponseVO = (MarketingResponseVo) result.getData();
		return ResponseMessage.ok(marketingResponseVO.getSurplusQuantity());

	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage bindBatchReceiveAccount(Long userId, String marketingBatchRelease) {
		List<TMarketingRelevant> relevantList = JSONArray.parseArray(marketingBatchRelease, TMarketingRelevant.class);
		for (TMarketingRelevant marketingRelevant : relevantList) {
			// 查询具体的券信息
			TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingRelevant.getSupportBusinessId(),
					marketingRelevant.getMarketingType());
			if (marketing == null) {
				throw new RuntimeException("查询无数据，id:" + marketingRelevant.getSupportBusinessId() + ",名称:"
						+ marketingRelevant.getServprodName());
			}
			String marketType = "券";
			if (marketing.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()) {
				marketType = "卡";
			}
			if (MarketingStatusEnum.UP.getCode() != marketing.getStatus()) {
				throw new RuntimeException(marketType + "未上架 id:" + marketingRelevant.getSupportBusinessId() + ",名称:"
						+ marketingRelevant.getServprodName());
			}
			if (marketingRelevant.getTotalQuantity() == null || marketingRelevant.getTotalQuantity().intValue() <= 0) {
				throw new RuntimeException(
						marketType + "id:" + marketing.getId() + ",名称:" + marketing.getName() + ",设置的数量必须大于0");
			}
			if (marketing.getStockQuantity().intValue() != 0 && marketing.getSurplusQuantity().intValue()
					- marketingRelevant.getTotalQuantity().intValue() < 0) {
				throw new RuntimeException("库存不足，" + marketType + "id:" + marketing.getId() + ",名称:"
						+ marketing.getName() + ",库存:" + marketing.getSurplusQuantity());
			}
		}
		List<TMarketingReceiveHistory> responseVoList = new ArrayList<TMarketingReceiveHistory>();
		for (TMarketingRelevant marketingRelevant : relevantList) {
			if (marketingRelevant.getTotalQuantity() == null || marketingRelevant.getTotalQuantity() <= 0) {
				throw new RuntimeException("券，卡数量为空");
			}
			// 查询具体的券信息
			TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingRelevant.getSupportBusinessId(),
					marketingRelevant.getMarketingType());
			if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
				throw new RuntimeException("券类型不合法,不能包含券包");
			}

			int count = marketingRelevant.getTotalQuantity();
			if (count > marketing.getSurplusQuantity().intValue()) {
				throw new RuntimeException("数量超出库存,id:" + marketing.getId());
			}
			// 领取规则验证
//			ResponseMessage message = marketingRuleReceiveValidation(userId, marketing);
//			if (message.getStatus() != ResponseMessage.ok().getStatus()) {
//				throw new RuntimeException(message.getMsg());
//			}
			for (int i = 0; i < count; i++) {
				// 构建领取记录
				MarketingReceiveHistoryParam marketingReceiveHistoryParam = new MarketingReceiveHistoryParam();
				marketingReceiveHistoryParam.setCreateBy(userId);
				marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.MANUAL.getCode());// 客服发券
				// 构建领取记录
				TMarketingReceiveHistory history = null;
				if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
					history = new TMarketingReceiveHistoryCoupon();
					buildNewReceiveHistory(marketingReceiveHistoryParam, marketing, null, history);
					tMarketingReceiveHistoryCouponMapper.insertSelective((TMarketingReceiveHistoryCoupon) history);
				} else if (marketing.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()) {
					history = new TMarketingReceiveHistoryCardWithBLOBs();
					buildNewReceiveHistory(marketingReceiveHistoryParam, marketing, null, history);
					tMarketingReceiveHistoryCardMapper.insertSelective((TMarketingReceiveHistoryCardWithBLOBs) history);
				} else if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
					history = new TMarketingReceiveHistoryCouponBag();
					buildNewReceiveHistory(marketingReceiveHistoryParam, marketing, null, history);
					tMarketingReceiveHistoryCouponBagMapper
							.insertSelective((TMarketingReceiveHistoryCouponBag) history);
				}
				// 券,卡库存新增变更记录
				String memo = "更新" + MarketingTypeEnum.parseStatus(marketing.getMarketingType()).getDesc()
						+ ",用户领取变更库存";
				inventoryService.addInventoryModificationRecord(marketing.getId(), history.getId(), 1, memo, userId,
						marketing.getMarketingType());
				if (i == 0) {
					responseVoList.add(history);
				}
			}
		}
		return ResponseMessage.ok(responseVoList);
	}

	@Override
	public ResponseMessage queryCouponBagDetailByItemId(MarketingParam marketingParam) {
		TMarketingCouponBagExample tMarketingExample = new TMarketingCouponBagExample();
		tMarketingExample.createCriteria().andThirdBizIdEqualTo(marketingParam.getThirdBizId())
				.andStatusEqualTo(Constant.STATUS_YES);
		List<TMarketingCouponBag> marketingList = tMarketingCouponBagMapper.selectByExample(tMarketingExample);
		if (CollectionUtils.isEmpty(marketingList)) {
			return ResponseMessage.error("查询券包信息为空", 500);
		}
		if (marketingList.size() > 1) {
			return ResponseMessage.error("查询券包信息不唯一", 500);
		}
		TMarketingCouponBag marketing = marketingList.get(0);
		MarketingResponseVo marketingResponseVO = new MarketingResponseVo();
		BeanUtils.copyProperties(marketing, marketingResponseVO);
		if(StringUtils.isNotBlank(marketingResponseVO.getStoreIds())) {
			String storeIds = marketingResponseVO.getStoreIds();
			if(storeIds.startsWith("0,")) {
				storeIds = storeIds.substring(2, storeIds.length());
			}
			if(storeIds.endsWith(",0")) {
				storeIds = storeIds.substring(0, storeIds.length()-2);
			}
			marketingResponseVO.setStoreIds(storeIds);
		}
		// 领取规则验证
		ResponseMessage message = marketingRuleReceiveValidation(marketingParam.getCreateBy(), marketing);
		return message.setData(marketingResponseVO);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage delayCompensateBindReceiveAccount(
			MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		List<TDictMarketing> dictMarketingList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(
				DictMarketingEnum.DELAY_COMPENSATE.name(), DictMarketingEnum.DELAY_COMPENSATE.getItemCodeV1());
		if (CollectionUtils.isEmpty(dictMarketingList)) {
			return ResponseMessage.error("不予补偿", 500);
		}
		// 仅限领取一次
		for (TDictMarketing dictMarketing : dictMarketingList) {
			if (dictMarketing.getItemType() != null && StringUtils.isNotBlank(dictMarketing.getItemValue())) {
				marketingReceiveHistoryParam.setMarketingType(dictMarketing.getItemType());
				marketingReceiveHistoryParam.setMarketingId(Long.parseLong(dictMarketing.getItemValue()));
				return receiveService.bindReceiveAccount(marketingReceiveHistoryParam);
			}
		}
		return ResponseMessage.error("不予补偿", 500);
	}

	@Override
	public ResponseMessage bindReceiveAccountOfHairdresserGive(
			MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		List<TDictMarketing> dictMarketingList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(
				DictMarketingEnum.HAIRDRESSER_MARKETING.name(),
				DictMarketingEnum.HAIRDRESSER_MARKETING.getItemCodeV1());
		if (CollectionUtils.isEmpty(dictMarketingList)) {
			return ResponseMessage.error("领取失败", 500);
		}
		// 仅限领取一次
		for (TDictMarketing dictMarketing : dictMarketingList) {
			if (dictMarketing.getItemType() != null && StringUtils.isNotBlank(dictMarketing.getItemValue())
					&& dictMarketing.getItemType().equals(marketingReceiveHistoryParam.getMarketingType())
					&& marketingReceiveHistoryParam.getMarketingId()
							.equals(Long.parseLong(dictMarketing.getItemValue()))) {
				marketingReceiveHistoryParam.setMarketingType(dictMarketing.getItemType());
				marketingReceiveHistoryParam.setMarketingId(Long.parseLong(dictMarketing.getItemValue()));
				return receiveService.bindReceiveAccount(marketingReceiveHistoryParam);
			}
		}
		return ResponseMessage.error("领取失败", 500);
	}

	@Override
	public ResponseMessage bindReceiveAccountOfShareNewUser(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		List<TDictMarketing> dictMarketingList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(
				DictMarketingEnum.C_TO_C_SHARE.name(), DictMarketingEnum.C_TO_C_SHARE.getItemCodeV1());
		if (CollectionUtils.isEmpty(dictMarketingList)) {
			return ResponseMessage.error("领取失败", 500);
		}
		// 仅限领取一次
		for (TDictMarketing dictMarketing : dictMarketingList) {
			if (dictMarketing.getItemType() != null && StringUtils.isNotBlank(dictMarketing.getItemValue())) {
				marketingReceiveHistoryParam.setMarketingType(dictMarketing.getItemType());
				marketingReceiveHistoryParam.setMarketingId(Long.parseLong(dictMarketing.getItemValue()));
				return receiveService.bindReceiveAccount(marketingReceiveHistoryParam);
			}
		}
		return ResponseMessage.error("领取失败", 500);
	}

	@Override
	public ResponseMessage bindReceiveAccountOfShareOldUser(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		List<TDictMarketing> dictMarketingList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(
				DictMarketingEnum.C_TO_C_SHARE.name(), DictMarketingEnum.C_TO_C_SHARE.getItemCodeV2());
		if (CollectionUtils.isEmpty(dictMarketingList)) {
			return ResponseMessage.error("领取失败", 500);
		}
		// 仅限领取一次
		for (TDictMarketing dictMarketing : dictMarketingList) {
			if (dictMarketing.getItemType() != null && StringUtils.isNotBlank(dictMarketing.getItemValue())) {
				marketingReceiveHistoryParam.setMarketingType(dictMarketing.getItemType());
				marketingReceiveHistoryParam.setMarketingId(Long.parseLong(dictMarketing.getItemValue()));
				return receiveService.bindReceiveAccount(marketingReceiveHistoryParam);
			}
		}
		return ResponseMessage.error("领取失败", 500);
	}

	@Override
	public ResponseMessage queryMarketingByHairdresserGive() {
		List<TDictMarketing> dictMarketingList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(
				DictMarketingEnum.HAIRDRESSER_MARKETING.name(),
				DictMarketingEnum.HAIRDRESSER_MARKETING.getItemCodeV1());
		if (CollectionUtils.isEmpty(dictMarketingList)) {
			return ResponseMessage.ok(dictMarketingList);
		}
		List<MarketingResponseVo> returnList = dictMarketingList.stream().map(this::queryReturnMarketing)
				.collect(Collectors.toList());
		return ResponseMessage.ok(returnList);
	}

	private MarketingResponseVo queryReturnMarketing(TDictMarketing dictMarketing) {
		// 卡，券信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(Long.parseLong(dictMarketing.getItemValue()), dictMarketing.getItemType());
		if (marketing == null) {
			return null;
		}
		MarketingResponseVo marketingResponseVO = new MarketingResponseVo();
		BeanUtils.copyProperties(marketing, marketingResponseVO);
		return marketingResponseVO;
	}

	@Override
	public ResponseMessage checkUserHasBarberCoupon(Long userId,String hairType) {
		List<TDictMarketing> dictMarketingList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(
				DictMarketingEnum.ORDER_AWARD.name(),null);
		if (CollectionUtils.isEmpty(dictMarketingList)) {
			return ResponseMessage.ok(Boolean.FALSE).setmsg("无可领取的奖励券");
		}
		List<Long> marketingIds = dictMarketingList.stream().filter(market ->StringUtils.isNotBlank(market.getItemValue())).map(marketing ->Long.parseLong(marketing.getItemValue())).collect(Collectors.toList());
		if(CollectionUtils.isEmpty(marketingIds)) {
			return ResponseMessage.ok(Boolean.FALSE).setmsg("无可领取的奖励券");
		}
		List<Long> userIds = userService.queryUserIdsByUserId(userId);
		if(CollectionUtils.isEmpty(userIds)) {
			userIds = new ArrayList<>();
			userIds.add(userId);
		}
		TMarketingReceiveHistoryCouponExample example = new TMarketingReceiveHistoryCouponExample();
		example.createCriteria()
			   .andUserIdIn(userIds)
			   .andMarketingIdIn(marketingIds)
			   .andStatusEqualTo(Constant.STATUS_YES)
			   .andUseEndTimeGreaterThanOrEqualTo(new Date());
		int count =tMarketingReceiveHistoryCouponMapper.countByExample(example);
		if(count<=0) {
			return ResponseMessage.ok(Boolean.FALSE).setmsg("账户内无有效的奖励券");
		}
		return ResponseMessage.ok(Boolean.TRUE).setmsg("账户内已有有效的奖励券");
	}
	@Override
	public ResponseMessage bindBarberReceiveAccount(Long userId,String hairType) {
		TMarketingReceiveHistoryCardExample example = new TMarketingReceiveHistoryCardExample();
		example.createCriteria()
			   .andUserIdEqualTo(userId)
			   .andServiceTypeEqualTo(MarketingServiceTypeEnum.FREE.getType())
			   .andStatusEqualTo(Constant.STATUS_YES)
			   .andUseEndTimeGreaterThanOrEqualTo(new Date());
		int hasFreeCardCount =tMarketingReceiveHistoryCardMapper.countByExample(example);
		String itemCode = DictMarketingEnum.ORDER_AWARD.getItemCodeV1();
		if(hasFreeCardCount>0) {
			itemCode=DictMarketingEnum.ORDER_AWARD.getItemCodeV2();
		}
		List<TDictMarketing> dictMarketingList = dictMarketingService.queryDictMarketingByTypeCodeAndItemCode(
				DictMarketingEnum.ORDER_AWARD.name(),itemCode);
		if (CollectionUtils.isEmpty(dictMarketingList)) {
			return ResponseMessage.error("未查询到数据", 500);
		}
		List<Long> userIds = userService.queryUserIdsByUserId(userId);
		if(CollectionUtils.isEmpty(userIds)) {
			userIds = new ArrayList<>();
			userIds.add(userId);
		}
		// 仅限领取一次
		for (TDictMarketing dictMarketing : dictMarketingList) {
			if (dictMarketing.getItemType() != null && StringUtils.isNotBlank(dictMarketing.getItemValue())) {
				//barber下单需验证账户内是否有可用的该券
				Boolean flag = hasReceiveMarketing(userIds,Long.parseLong(dictMarketing.getItemValue()),dictMarketing.getItemType());
				if(!flag) {
					MarketingReceiveHistoryParam marketingReceiveHistoryParam =new MarketingReceiveHistoryParam();
					marketingReceiveHistoryParam.setMarketingType(dictMarketing.getItemType());
					marketingReceiveHistoryParam.setMarketingId(Long.parseLong(dictMarketing.getItemValue()));
					marketingReceiveHistoryParam.setCreateBy(userId);
					marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.PAY_GIVE.getCode());
					return receiveService.bindReceiveAccount(marketingReceiveHistoryParam);
				}
			}
		}
		return ResponseMessage.error("领取失败", 500);
	}

	private Boolean hasReceiveMarketing(List<Long> userIds, Long marketingId, Integer marketingType) {
		int count = 0;
		if(MarketingTypeEnum.COUPON.getCode() == marketingType.intValue()) {
			TMarketingReceiveHistoryCouponExample example = new TMarketingReceiveHistoryCouponExample();
			example.createCriteria()
				   .andUserIdIn(userIds)
				   .andMarketingIdEqualTo(marketingId)
				   .andStatusEqualTo(Constant.STATUS_YES)
				   .andUseEndTimeGreaterThanOrEqualTo(new Date());
		    count = count + tMarketingReceiveHistoryCouponMapper.countByExample(example);
		}
		if(MarketingTypeEnum.CARD.getCode() == marketingType.intValue()) {
			TMarketingReceiveHistoryCardExample example = new TMarketingReceiveHistoryCardExample();
			example.createCriteria()
				   .andUserIdIn(userIds)
				   .andMarketingIdEqualTo(marketingId)
				   .andStatusEqualTo(Constant.STATUS_YES)
				   .andUseEndTimeGreaterThanOrEqualTo(new Date());
		    count = count + tMarketingReceiveHistoryCardMapper.countByExample(example);
		}
		return count>0;
	}
}
